package a07_二叉树;

/**
 * <p>
 * a18_从中序与后序遍历序列构造二叉树复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/2/18
 */
public class a18_从中序与后序遍历序列构造二叉树复习2 {

    public static void main(String[] args) {
        a18_从中序与后序遍历序列构造二叉树复习2 test = new a18_从中序与后序遍历序列构造二叉树复习2();
        test.buildTree( new int[]{9,3,15,20,7},new int[]{9,15,7,20,3});
    }
    //左中右inorder = [9,3,15,20,7],
    //左右中postorder = [9,15,7,20,3]

    //取3到inorder找，分成9   15,20,7
    //去postorder分 9 15,7,20
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder.length == 0){
            return null;
        }

        int rootVal = postorder[postorder.length-1];
        TreeNode rootNode = new TreeNode(rootVal);

        int rootIdx = 0;
        for (int i = 0; i < inorder.length; i++) {
            if(inorder[i] == rootVal){
                rootIdx = i;
            }
        }

        int[] leftInorder = spiltArray(inorder, 0, rootIdx-1);
        int[] rightInorder = spiltArray(inorder, rootIdx+1, inorder.length-1);

        int[] leftPostorder = spiltArray(postorder, 0, leftInorder.length - 1);
        int[] rightPostorder = spiltArray(postorder, rootIdx, postorder.length - 2);

        rootNode.left = buildTree(leftInorder, leftPostorder);
        rootNode.right = buildTree(rightInorder, rightPostorder);
        return rootNode;
    }

    private int[] spiltArray(int[] array,int leftIdx,int rightIdx){
        System.out.println("leftIdx = " + leftIdx);
        System.out.println("rightIdx = " + rightIdx);
        int[] result = new int[rightIdx - leftIdx + 1];
        int currentIdx = 0;
        while (leftIdx <= rightIdx){
            result[currentIdx] = array[leftIdx];
            leftIdx++;
            currentIdx++;
        }
        return result;
    }
}
